package homework021.dao;

import homework021.domain.Goods;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 商品DAO
 *
 * @author itheima
 */
public class GoodsDaoImpl implements GoodsDao {

    private final static String SOURCE = "src\\day17\\homework021\\goods.txt";

    @Override
    public boolean add(Goods goods) throws IOException {
        // 从文档读取商品数据
        List<Goods> goodList = findAll();
        goodList.add(goods);

        // 将列表数据转为字符串存入文档
        refreshToFile(goodList);

        return true;
    }

    @Override
    public boolean deleteByIndex(int index) throws IOException {
        // 从文档读取商品数据
        List<Goods> goodList = findAll();
        goodList.remove(index);

        // 将列表数据转为字符串存入文档
        refreshToFile(goodList);

        return true;
    }

    @Override
    public boolean update(int index, Goods goods) throws IOException {

        // 通过索引,通过id去查询数据
        List<Goods> goodList = findAll();

        Goods goods1 = goodList.get(index);
        goods1.setId(goods.getId());
        goods1.setName(goods.getName());
        goods1.setPrice(goods.getPrice());
        goods1.setWeight(goods.getWeight());

        goodList.set(index, goods1);

        // 将列表数据转为字符串存入文档
        refreshToFile(goodList);

        return true;
    }

    @Override
    public List<Goods> findAll() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(SOURCE));
        List<Goods> goodsList = new ArrayList<>();
        while (true) {
            String goodsInfo = bufferedReader.readLine();
            if (Objects.isNull(goodsInfo)) {
                break;
            }

            String[] goodsArray = goodsInfo.split(",");
            Goods goods = new Goods(goodsArray[0], goodsArray[1], goodsArray[2], goodsArray[3]);
            goodsList.add(goods);
        }

        bufferedReader.close();

        return goodsList;
    }

    private void refreshToFile(List<Goods> list) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(SOURCE));
        for (Goods goods : list) {
            bufferedWriter.write(goods.getId() + "," + goods.getName() + "," + goods.getPrice() + "," + goods.getWeight());
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
    }
}
